package com.common.interceotpr;

import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.dto.ReturnDto;
import com.common.util.ConstantErrCode;
import com.common.util.ConstantInit;
import com.common.util.ConstantWebContext;
import com.common.util.FormatUtil;
import com.common.util.ToolIDEA;
import com.common.util.ToolWeb;
import com.demo.common.model.User;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;

public class AuthInterceptor implements Interceptor {

	/**
	 * 加密登陆token
	 * 
	 * @param request
	 * @param response
	 * @param user
	 * @param autotologin
	 */
	public static void setCurrentUser(HttpServletRequest request, HttpServletResponse response, User user,
			boolean autotologin) {
		// 1.设置cookie的有效时间
		int maxAgeTemp = -1;
		if (autotologin) {
			maxAgeTemp = PropKit.getInt(ConstantInit.config_maxAge_key);
		}

		// 2.设置用户名到cookie
		ToolWeb.addCookie(response, "", "/", true, "username", user.getUsername(), maxAgeTemp);

		// 3.生成登陆认证cookie
		int userId = user.getId();
		String ips = ToolWeb.getIpAddr(request);
		String userAgent = request.getHeader("User-Agent");
		long date = new Date().getTime();

		StringBuilder token = new StringBuilder();// 时间戳.#.USERID.#.USER_IP.#.USER_AGENT.#.autoLogin
		token.append(date).append(".#.").append(userId).append(".#.").append(ips).append(".#.").append(userAgent)
				.append(".#.").append(autotologin);
		String authmark = ToolIDEA.encrypt(token.toString());

		// 4.添加到token
		ToolWeb.addCookie(response, "", "/", true, ConstantWebContext.cookie_authmark, authmark, maxAgeTemp);
	}

	/**
	 * 解密登陆token
	 * 
	 * @param request
	 * @param response
	 * @param userAgentVali
	 * @return
	 */
	public static User getCurrentUser(HttpServletRequest request, HttpServletResponse response, boolean userAgentVali) {
		String loginCookie = ToolWeb.getCookieValueByName(request, ConstantWebContext.cookie_authmark);
		if (null != loginCookie && !loginCookie.equals("")) {
			// 1.解密数据
			String data = ToolIDEA.decrypt(loginCookie);
			String[] datas = data.split(".#.");// arr[0]:时间戳,arr[1]:USERID,arr[2]:USER_IP,arr[3]:USER_AGENT

			// 2.分解获取数据
			long loginDateTimes = Long.parseLong(datas[0]);
			int userId = Integer.parseInt(datas[1]);
			String ips = datas[2];
			String userAgent = datas[3];
			boolean autoLogin = Boolean.parseBoolean(datas[4]);

			String newIp = ToolWeb.getIpAddr(request);
			String newUserAgent = request.getHeader("User-Agent");

			Date start = new Date();
			start.setTime(loginDateTimes);
			int day = FormatUtil.getDateDaySpace(start, FormatUtil.getDate());

			int maxAge = PropKit.getInt(ConstantInit.config_maxAge_key);

			// 3.验证数据的有效性
			if (ips.equals(newIp) && (userAgentVali ? userAgent.equals(newUserAgent) : true) && day <= maxAge) {
				// 如果不记住密码，单次登陆有效时间验证
				if (!autoLogin) {
					int minute = FormatUtil.getDateMinuteSpace(start, FormatUtil.getDate());
					int session = PropKit.getInt(ConstantInit.config_session_key);
					if (minute > session) {
						return null;
					} else {
						// 重新生成认证cookie,目的是更新时间戳
						long date = FormatUtil.getDateTime();
						StringBuilder token = new StringBuilder();
						token.append(date).append(".#.").append(userId).append(".#.").append(ips).append(".#.")
								.append(userAgent).append(".#.").append(autoLogin);
						String authmark = ToolIDEA.encrypt(token.toString());

						// 添加到cookie
						int maxAgeTemp = -1;
						ToolWeb.addCookie(response, "", "/", true, ConstantWebContext.cookie_authmark, authmark,
								maxAgeTemp);
					}
				}

				// 返回用户数据
				return User.dao.findById(userId);
			}
		}
		return null;
	}

	@Override
	public void intercept(Invocation inv) {
		ReturnDto rtDto = new ReturnDto();
		Controller controller = inv.getController();
		try {
			User user = getCurrentUser(controller.getRequest(), controller.getResponse(), true);
			if (user != null) {
				inv.invoke();
			} else {
				rtDto.setErrCode(ConstantErrCode.NO_LOGIN);
				throw new IllegalArgumentException("请登陆!");
			}
		} catch (Exception e) {
			rtDto.setErrMsg(e.getMessage());
			rtDto.setSuccess(false);
			rtDto.setRows(new ArrayList());	
			controller.renderJson(rtDto);
		}
	}

	public static int getUserId(HttpServletRequest request) {
		String loginCookie = ToolWeb.getCookieValueByName(request, ConstantWebContext.cookie_authmark);
		// 1.解密数据
		String data = ToolIDEA.decrypt(loginCookie);
		String[] datas = data.split(".#.");// arr[0]:时间戳,arr[1]:USERID,arr[2]:USER_IP,arr[3]:USER_AGENT

		return Integer.parseInt(datas[1]);
	}

}
